package com.heima.wemedia.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.feign.article.IArticleClient;
import com.heima.feign.user.IUserClient;
import com.heima.model.comment.dtos.*;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.pojos.ApComment;
import com.heima.wemedia.pojos.ApCommentRepay;
import com.heima.wemedia.pojos.CommentRepayListVo;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.pojos.ApComment;
import com.heima.wemedia.pojos.ApCommentLike;
import com.heima.wemedia.pojos.ApCommentRepay;
import com.heima.wemedia.pojos.ApCommentRepayLike;
import com.heima.wemedia.service.CommentManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j

public class CommentManageServiceImpl implements CommentManageService {
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IUserClient userClient;
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 功能描述：评论开启和关闭 0 关闭评论 1 开启评论
     *
     * @param dto
     * @return {@link ResponseResult }
     * @author sungang
     * @date 2024/01/27  23:17
     */

    @Override
    public ResponseResult updateCommentStatus(CommentConfigDto dto) {
        //参数校验
        if(dto==null){
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        WmUser wmUser = WmThreadLocalUtil.getUser();
        //app端用户id
        WmUser userser = wmUserMapper.selectById(wmUser.getId());
        Integer apUserId = userser.getApUserId();
        //查询该文章的所有评论
        List<ApComment> apCommentList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(dto.getArticleId())
                .and("authorId").is(apUserId)), ApComment.class);
        //遍历文章
        for (ApComment apComment : apCommentList) {
            List<ApCommentRepay> commentRepayList = mongoTemplate.find(Query.query(Criteria.where("commentId")
                    .is(apComment.getId()).and("authorId").is(apUserId)), ApCommentRepay.class);
            List<String> commentRepayIdList = commentRepayList.stream()
                    .map(ApCommentRepay::getId).distinct().collect(Collectors.toList());
            //删除所有的评论回复点赞数据
            mongoTemplate.remove(Query.query(Criteria.where("commentRepayId")
                    .in(commentRepayIdList).and("authorId").is(apUserId)), ApCommentRepayLike.class);
            //删除该评论的所有的回复内容
            mongoTemplate.remove(Query.query(Criteria.where("commentId")
                    .is(apComment.getId()).and("authorId").is(apUserId)), ApCommentRepay.class);
            //删除评论的点赞
            mongoTemplate.remove(Query.query(Criteria.where("commentId")
                    .is(apComment.getId()).and("authorId").is(apUserId)), ApCommentLike.class);
        }
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(dto.getArticleId())
                .and("authorId").is(apUserId)),ApComment.class);
        //修改app文章的config配置
        return iArticleClient.updateCommentStatus(dto);
    }

    @Override
    public PageResponseResult findNewsComment(CommentNewsQueryDto dto) {
        WmUser user = WmThreadLocalUtil.getUser();
        dto.setWmUserId(user.getId());
        return iArticleClient.findnewsQueryComents(dto);
    }

    /**
     * @param dto :
     * @return ResponseResult<?>
     * @author 18297
     * @date 2024/1/27 22:33
     * @description 作者回复评论
     */
    @Override
    public ResponseResult<?> saveCommentRepay(CommentRepaySaveDto dto) {
        //1.检查参数
        if(dto == null || StringUtils.isBlank(dto.getContent()) || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容不能超过140字");
        }


        //获取自媒体人信息
        WmUser wmUser = WmThreadLocalUtil.getUser();
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        if(dbUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取app端用户信息
        ApUser apUser = userClient.findUserById(dbUser.getApUserId());
//        ApUser apUser = userClient.findUserById(1102);
        //3.保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setCommentId(dto.getCommentId());

        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);
        log.info("结束方法前");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param dto :
     * @return ResponseResult
     * @author 18297
     * @date 2024/1/27 22:55
     * @description 作者点赞评论
     */
    @Override
    public ResponseResult<?> like(CommentLikeDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 通过评论id查询到对应评论对象
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);

        //获取自媒体人信息
        WmUser wmUser = WmThreadLocalUtil.getUser();
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        if(dbUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //远程调用，获取app端用户信息
        ApUser apUser = userClient.findUserById(dbUser.getApUserId());
//        ApUser apUser = userClient.findUserById(4);

        //3.点赞
        if (apComment != null && dto.getOperation() == 0) {
            //更新评论点赞数量
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            //保存评论点赞数据
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(apUser.getId());
            mongoTemplate.save(apCommentLike);
        } else {
            //更新评论点赞数量
            int tmp = apComment.getLikes() - 1;
            // 点赞最少为0
            tmp = tmp < 1 ? 0 : tmp;
            apComment.setLikes(tmp);
            mongoTemplate.save(apComment);

            //删除评论点赞
            Query query = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUser.getId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }

        //4.取消点赞
        Map<String, Object> result = new HashMap<>();
        result.put("likes", apComment.getLikes());
        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult deleteComment(String commentId) {
        //检查参数
        if(StringUtils.isBlank(commentId)){
         return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentId)), ApComment.class);
        mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)), ApCommentRepay.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult deleteCommentRepay(String commentRepayId) {
        //检查参数
        if(StringUtils.isBlank(commentRepayId)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //删除评论回复
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentRepayId)),ApCommentRepay.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看评论回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(CommentManageDto dto) {
        //1.校验参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 获取请求参数
        Integer page = dto.getPage();
        Integer size = dto.getSize();

        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()))
                .with(PageRequest.of(page-1,size))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));

        List<ApComment> list = mongoTemplate.find(query, ApComment.class);

        List<CommentRepayListVo> commentRepayListVos = new ArrayList<>();

        for (ApComment apComment : list) {
            CommentRepayListVo commentRepayListVo = new CommentRepayListVo();
            commentRepayListVo.setApComments(apComment);
            Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime"));
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query1, ApCommentRepay.class);
            commentRepayListVo.setApCommentRepays(apCommentRepays);
            commentRepayListVos.add(commentRepayListVo);
        }
        return ResponseResult.okResult(commentRepayListVos);
    }
}
